'use strict';
// let appid = 'wx9ac8eecf404e43f1'
// let secret = 'a5b082cce4eee32e86ab43a46ba91229'

const {
	getWxAppid,
	getSecret
} = require('security')
let wxappid = getWxAppid('wx')
let wxSecret = getSecret('wx')
let qqappid = getWxAppid('qq')
let qqSecret = getSecret('qq')
exports.main = async (event, context) => {
	uniCloud.logger.info(event.type)
	//event为客户端上传的参数
	if (event.type == 'wx') {

		let result = await WxGetOpenidByCode(event.code)
		return result
	}
	if (event.type == 'qq') {

		let result = await qqGetOpenidByCode(event.code)
		return result
	}
	//返回数据给客户端
};


function WxGetOpenidByCode(code) {
	return new Promise(async resolve => {
		let res = await uniCloud.httpclient.request(
			`https://api.weixin.qq.com/sns/jscode2session?appid=${wxappid}&secret=${wxSecret}&js_code=${code}&grant_type=authorization_code`, {
				dataType: 'json'
			}
		)
		uniCloud.logger.info(res)
		resolve(res.data.openid)
	})

}

function qqGetOpenidByCode(code) {
	return new Promise(async resolve => {
		let res = await uniCloud.httpclient.request(
			`https://api.q.qq.com/sns/jscode2session?appid=${qqappid}&secret=${qqSecret}&js_code=${code}&grant_type=authorization_code`, {
				dataType: 'json'
			}
		)
		uniCloud.logger.info(qqappid,qqSecret)
		resolve(res.data.openid)
	})

}
